<template>
  <!-- 材料费 -->
  <section>
    <div style="text-align:right;">
      <el-select
        v-model="templateForm.curTemplate"
        style="width:300px;"
        value-key="id"
        filterable
        remote
        :remote-method="templatePage"
        clearable
        @clear="templatePage"
        @change="onChangeTemplate"
        placeholder="选择模板"
      >
        <el-option
          v-for="(item, index) in templateForm.templateArr"
          :key="index"
          :value="item"
          :label="item.name"
        ></el-option>
        <br />
        <pager
          v-model="templateForm.pager"
          small
          @change-pagenum="getTemplate"
        ></pager>
      </el-select>
    </div>
    <br />
    <el-form :model="form" ref="form">
      <table class="table-box">
        <thead>
          <tr>
            <th>名称</th>
            <th>规格</th>
            <th>单位</th>
            <th>库存</th>
            <th>数量</th>
            <th>说明</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in form.list" :key="index">
            <td>
              <el-tooltip
                :disabled="!item.price"
                effect="dark"
                :content="'￥' + item.price"
                placement="top"
              >
                <el-link :underline="false" type="primary">{{
                  item.name
                }}</el-link>
              </el-tooltip>
            </td>
            <td>{{ item.specification }}</td>
            <td>{{ item.unit | changeAssist(unitEnum) }}</td>
            <td>
              {{ item.packNum }}{{ item.packUnit | changeAssist(unitEnum) }}
            </td>
            <td>
              <el-form-item
                :prop="'list.' + index + '.materialNum'"
                :rules="[rulesRequired, rulesNumber]"
              >
                <el-input
                  v-model.number="item.materialNum"
                  type="number"
                  :disabled="toDisabled(item)"
                  style="width:100px"
                ></el-input>
              </el-form-item>
            </td>
            <td>
              <el-input
                v-model="item.remark"
                :disabled="toDisabled(item)"
              ></el-input>
            </td>
            <td>
              <el-link
                v-if="!toDisabled(item)"
                :underline="false"
                class="vertical-middle"
                @click.prevent="onDelItem(item, index)"
              >
                <i class="el-icon-delete"></i>
              </el-link>
            </td>
          </tr>
        </tbody>
      </table>
    </el-form>
    <div
      v-if="form.list.length == 0"
      style="color:#999;padding:10px 0;text-align:center;"
    >
      <i class="iconfont iconwushuju" style="font-size:40px;"></i>
      <div>暂无数据</div>
    </div>
    <br />
    <div>
      <el-select
        v-model="curItem"
        value-key="id"
        filterable
        remote
        clearable
        @clear="pageQueryWithInventory"
        :remote-method="pageQueryWithInventory"
        @change="onChangeItem"
        placeholder="请选择材料费"
        style="width:100%"
      >
        <el-option
          v-for="(item, index) in materialFeeArr"
          :key="index"
          :label="item.name"
          :value="item"
        ></el-option>
        <br />
        <pager v-model="pager" @change-pagenum="getPage"></pager>
      </el-select>
    </div>
    <br />
    <div class="form-tool">
      <div>
        <el-button type="primary" :loading="btnLoading" @click="onSubmit"
          >保存</el-button
        >
      </div>
      <div>
        <el-button
          v-if="form.list.length > 0 && !templateSave.t5"
          @click="printFee = true"
        >
          <i
            class="iconfont icondayin vertical-middle"
            style="font-size:20px;"
          ></i>
          <span class="vertical-middle">打印材料请单</span>
        </el-button>
      </div>
    </div>
    <materialFee
      v-model="printFee"
      :list="form.list"
      :cureId="cureId"
      :patientId="patientId"
    ></materialFee>
  </section>
</template>
<script>
export default {
  components: {
    materialFee: () => import("../_print/materialFee.vue")
  },
  computed: {
    templateSave() {
      return this.$store.state.doctorMZ.templateSave;
    },
    templateData() {
      return this.$store.state.doctorMZ.templateData;
    },
    unitEnum() {
      return this.$store.state.doctorMZ.enum.unitEnum;
    },
    patientId() {
      return this.$store.state.doctorMZ.patientId;
    },
    doctorId() {
      return this.$store.state.doctorMZ.doctorId;
    },
    deptId() {
      return this.$store.state.doctorMZ.deptId;
    },
    cureId() {
      return this.$store.state.doctorMZ.cureId;
    }
  },
  data() {
    return {
      pager: { pageSize: 10, pageNum: 1, total: 0 },
      searchForm: {
        name: "",
        status: 0
      },
      templateForm: {
        name: "",
        pager: { pageSize: 10, pageNum: 1, total: 0 },
        //选择的模板
        curTemplate: null,
        templateArr: []
      },
      printFee: false,
      isOpenEdit: false,
      cureMedicalRelateId: "",
      btnLoading: false,
      form: {
        list: []
      },
      curItem: "",
      materialFeeArr: [],
      rulesRequired: {
        required: true,
        message: "此项必填",
        trigger: ["blur", "change"]
      },
      rulesNumber: {
        message: "格式有误",
        type: "number",
        min: 1,
        trigger: ["blur", "change"]
      }
    };
  },
  created() {
    // let th = this;
  },
  mounted() {
    let th = this;
    th.getData();
    th.templatePage();
    th.pageQueryWithInventory();
  },
  methods: {
    onSubmit() {
      let th = this;
      if (!th.cureMedicalRelateId && th.form.list.length == 0) return;
      let update = function() {
        let j = {
          cureMedicalRelateId: th.cureMedicalRelateId,
          cureMaterials: JSON.stringify(th.form.list)
        };
        th.btnLoading = true;
        th.$api
          .updateCureMaterial(j)
          .then(res => {
            if (res.executed) {
              th.$message.success("保存完成");
              th.getData("reset");
            } else {
              th.$message.error(res.message);
            }
            th.btnLoading = false;
          })
          .catch(() => {
            th.btnLoading = false;
          });
      };
      let add = function() {
        let j = {
          cureMedicalRelateId: th.cureMedicalRelateId,
          cureMaterials: JSON.stringify(th.form.list)
        };
        th.btnLoading = true;
        th.$api
          .addMultipleCureMaterial(j)
          .then(res => {
            if (res.executed) {
              th.$message.success("保存完成");
              th.getData("reset");
            } else {
              th.$message.error(res.message);
            }
            th.btnLoading = false;
          })
          .catch(() => {
            th.btnLoading = false;
          });
      };
      th.$refs["form"].validate(v => {
        if (v) {
          th.isOpenEdit = false;
          if (th.cureMedicalRelateId) update();
          else add();
        }
      });
    },
    //选择材料
    onChangeItem(obj) {
      let th = this;
      if (!obj) return;
      let j = {
        cureId: th.cureId,
        hpId: th.adminUser.hpId,
        patientId: th.patientId,
        deptId: th.deptId,
        doctorId: th.doctorId,
        materialId: obj.id,
        materialNum: "",
        id: "",
        name: obj.name,
        specification: obj.specification,
        unit: obj.unit,
        materialMoney: obj.retailPrice,
        remark: ""
      };
      if (obj.inventoryStatisticVO) {
        j.packNum = obj.inventoryStatisticVO.packNum;
        j.packUnit = obj.inventoryStatisticVO.packUnit;
      }
      th.addItem(j);
    },
    //选择模板
    onChangeTemplate(obj) {
      let th = this;
      if (!obj) return;
      let fn = function() {
        obj.materialTemplateItemVOS.forEach(item => {
          let j = {
            cureId: th.cureId,
            hpId: th.adminUser.hpId,
            patientId: th.patientId,
            deptId: th.deptId,
            doctorId: th.doctorId,
            materialId: item.materialId,
            materialNum: item.count,
            id: "",
            name: item.name,
            specification: item.spec,
            unit: item.unit,
            materialMoney: "",
            remark: item.desc
          };
          if (item.inventoryStatisticVO) {
            j.packNum = item.inventoryStatisticVO.packNum;
            j.packUnit = item.inventoryStatisticVO.packUnit;
          }
          th.addItem(j);
        });
      };
      fn();
    },
    onDelItem(obj, index) {
      let th = this;
      if (obj.id) {
        let j = {
          cureCheckupId: obj.id
        };
        th.$api.cureMaterialpreDelete(j).then(res => {
          if (res.executed && res.data) {
            th.form.list.splice(index, 1);
          } else {
            th.$message.warning(res.message);
          }
        });
      } else {
        th.form.list.splice(index, 1);
      }
    },
    //查询模板
    templatePage(name) {
      const th = this;
      th.templateForm.pager.pageNum = 1;
      th.templateForm.name = name;
      th.getTemplate();
    },
    //查询模板分页
    getTemplate() {
      let th = this;
      let j = {
        name: th.templateForm.name
      };
      Object.assign(j, th.templateForm.pager);
      th.$api.materialTemplatePageQuery(j).then(res => {
        if (res.executed) {
          th.templateForm.templateArr = res.dataBody.list;
          th.templateForm.pager.total = res.dataBody.total;
        }
      });
    },
    getData(reset) {
      let th = this;
      let j = {
        cureId: th.cureId
      };
      th.$api.getCureMaterialCureId(j).then(res => {
        if (reset) {
          th.form.list = [];
        }
        res.data.forEach((item, index) => {
          if (index == 0) th.cureMedicalRelateId = item.cureMedicalRelateId;
          let j = {
            cureId: th.cureId,
            hpId: th.adminUser.hpId,
            patientId: th.patientId,
            deptId: th.deptId,
            doctorId: th.doctorId,
            materialId: item.cureMaterialInfo.materialId,
            materialNum: item.cureMaterialInfo.materialNum,
            id: item.cureMaterialInfo.id,
            name: item.name,
            specification: item.specification,
            unit: item.unit,
            materialMoney: "",
            status: item.cureMaterialInfo.status,
            payStatus: item.payStatus,
            price: item.price ? Number.parseFloat(item.price) : 0,
            remark: item.cureMaterialInfo.remark,
            packNum: item.packNum,
            packUnit: item.packUnit
          };
          th.form.list.push(j);
        });
        th.$nextTick(function() {
          th.isOpenEdit = true;
          if (reset) {
            th.$store.commit("Set_templateSave", {
              key: "t5",
              value: false
            });
          }
        });
      });
    },
    getPage() {
      let th = this;
      let j = {
        hpId: th.adminUser.hpId
      };
      Object.assign(j, th.searchForm, th.pager);
      th.$api.pageQueryWithInventory(j).then(res => {
        if (res.executed) {
          if (res.dataBody.list) {
            th.materialFeeArr = res.dataBody.list;
            th.pager.total = res.dataBody.total;
          }
        }
      });
    },
    pageQueryWithInventory(name) {
      let th = this;
      th.pager.pageNum = 1;
      th.searchForm.name = name;
      th.getPage();
    },
    //添加项目
    addItem(json) {
      const th = this;
      if (typeof json.payStatus == "undefined") {
        json.payStatus = 2;
      }
      if (typeof json.status == "undefined") {
        json.status = 0;
      }
      if (json.payStatus == 2 && json.status == 0) {
        //判断库存
        if (th.inventoryflaw(json) == false) {
          return;
        }
        let data = th.form.list.find(d => {
          return d.materialId == json.materialId && d.payStatus === 2;
        });
        if (data) return;
        th.form.list.push(json);
      } else {
        th.form.list.push(json);
      }
    },
    //处理库存不足
    inventoryflaw(json) {
      const th = this;
      let bo = true; //默认库存足够
      if (json.payStatus == 2) {
        if (!json.packNum || json.packNum <= 0) {
          th.$message.warning(json.name + "库存不足");
          //还原状态
          bo = false;
        }
      }
      //如果库存不足将去掉红点
      if (bo == false) {
        //判断list是否为空
        if (th.form.list.length == 0) {
          th.$store.commit("Set_templateSave", {
            key: "t5",
            value: false
          });
        }
      }
      return bo;
    },
    //清空未付款的数据或未领取
    delListData() {
      const th = this;
      let newArr = th.form.list.filter(d => {
        return d.payStatus != 2 || d.status == 1;
      });
      th.form.list = newArr;
    },
    //判断是否已执行
    toDisabled(obj) {
      if (obj.payStatus == 2 && obj.status == 0) {
        return false;
      } else {
        return true;
      }
    }
  },
  watch: {
    form: {
      deep: true,
      handler: function(n) {
        let th = this;
        if (!th.isOpenEdit) return;
        let bo = true;
        if (n.list.length == 0 && !th.cureMedicalRelateId) {
          bo = false;
        }
        //开启修改状态
        th.$store.commit("Set_templateSave", {
          key: "t5",
          value: bo
        });
      }
    },
    //监听大模板数据
    templateData: {
      deep: true,
      immediate: true,
      handler(n) {
        const th = this;
        let data = n.t5;
        //判断是否有值
        if (!data) {
          return;
        }
        //清空数据
        if (n.isEmpty) {
          th.delListData();
        }
        data.forEach(ele => {
          //添加数据
          let j = {
            cureId: th.cureId,
            hpId: th.adminUser.hpId,
            patientId: th.patientId,
            deptId: th.deptId,
            doctorId: th.doctorId,
            materialId: ele.id,
            materialNum: 1,
            id: "",
            name: ele.name,
            specification: ele.specification,
            unit: ele.unit,
            materialMoney: "",
            price: ele.retailPrice,
            remark: "",
            packNum: "",
            packUnit: ""
          };
          if (ele.inventoryStatisticVO) {
            j.packNum = ele.inventoryStatisticVO.packNum;
            j.packUnit = ele.inventoryStatisticVO.packUnit;
          }
          th.addItem(j);
        });
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.item-box {
  background-color: #f3f3f3;
  margin: 0;
  padding: 9px 10px;
  border-radius: 7px;
  cursor: pointer;
}
.el-form-item {
  margin-bottom: 0;
}
</style>
